<?php

namespace App\Transformers\Frontend;

use App\Models\Order\Order;
use App\Models\Video;
use League\Fractal\TransformerAbstract;

class VideoTransformer extends TransformerAbstract
{

    protected $availableIncludes = ['imaging', 'videoing', 'teacher', 'follow'];

    protected $hidden = ['image', 'video', 'category_id', 'teacher_id', 'author_id'];

    public function transform(Video $model)
    {
        $model->makeHidden($this->hidden);
        return $model->attributesToArray() + [
                'count' => $model->sumOrder()
            ];
    }

    public function includeImaging(Video $model)
    {
        $image = $model->imaging;
        if (!$image) {
            return $this->null();
        }
        return $this->item($image, new FileTransformer());
    }

    public function includeVideoing(Video $model)
    {
        $video = $model->videoing;
        if (!$video) {
            return $this->null();
        }
        if ($model->price !== 0) {
            if (\Auth::user()) {
                $orders = Order::with('item')->where('state', Order::ORDER_PAY)
                    ->where('author_id', \Auth::user()->id)->get();
                $orders = $orders->filter(function (Order $order) use ($model) {
                    return $order->item->video_id === $model->id;
                });
                if ($orders->isEmpty()) {
                    return $this->null();
                }
            }
        }
        if (!$video->is_upload) {
            $video->path = env('FILE_PATH_URL') . $video->path;
        } else {
            $video->path = 'http://' . $video->config->url . '/' . $video->name;
        }
        return $this->item($video, new FileTransformer());
    }

    public function includeTeacher(Video $model)
    {
        $teacher = $model->teacher;
        if (!$teacher) {
            return $this->null();
        }
        return $this->item($teacher, new TeacherTransformer());
    }

    public function includeFollow(Video $model)
    {
        $follow = $model->follow;
        if (!$follow) {
            return $this->null();
        }
        return $this->item($follow, new FollowTransformer());
    }
}